<template>
  <div class="app-container">
    <el-form :model="device" label-width="100px">
      <el-form-item :label="$t('product')">
        <el-select v-model="device.productId" @change="productChange">
          <el-option
            v-for="item in productList"
            :key="item.productId"
            :label="item.name"
            :value="item.productId"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('series')">
        <el-select v-model="device.seriesId">
          <el-option
            v-for="item in productSeriesList"
            :key="item.seriesId"
            :label="item.name"
            :value="item.seriesId"
          />
        </el-select>
        <el-button type="primary" icon="el-icon-plus" @click="clickProductSeries" />
      </el-form-item>
      <el-form-item :label="$t('server')">
        <el-select v-model="device.serverId">
          <el-option
            v-for="item in serverList"
            :key="item.serverId"
            :label="item.name"
            :value="item.serverId"
          >
            <span style="float: left">{{ item.name }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{ item.serverMessage }}</span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('protocol')">
        <el-autocomplete
          v-model="device.protocol"
          class="inline-input"
          :fetch-suggestions="queryProtocolSearch"
        />
      </el-form-item>
      <el-form-item :label="$t('device')+$t('name')">
        <el-input v-model="device.deviceName" />
      </el-form-item>
      <el-form-item :label="$t('deviceCore')">
        <el-tooltip
          class="item"
          effect="dark"
          content="确认设备ID的唯一性，一旦出厂后输入后就无法更改只能删除该设备"
          placement="top-start"
        >
          <el-autocomplete
            v-model="device.deviceCore"
            class="inline-input"
            :fetch-suggestions="querySearch"
            @select="deviceCoreSelect"
          />
        </el-tooltip>
      </el-form-item>
      <el-form-item :label="$t('icon')">
        <el-input v-model="device.iconUrl">
          <template slot="prepend">
            <el-image
              style="width: 23px;height: 23px"
              :src="device.iconUrl"
            />
          </template>
          <template slot="append">
            <i class="el-icon-caret-bottom" @click="choseIcon" />
          </template>
        </el-input>
        <div v-show="isIconOpen">
          <el-image
            v-for="(item,index) in iconList"
            :key="index"
            style="cursor: pointer;width: 40px;height: 40px;margin: 5px"
            :src="item.url"
            @click="changeIco(item.url,200145308)"
          />
        </div>
      </el-form-item>
      <el-form-item :label="$t('remark')">
        <el-input v-model="device.remark" />
      </el-form-item>
      <el-form-item :label="$t('send')+$t('interval')">
        <el-slider v-model="device.sendInterval" show-input show-stops :max="30" />
      </el-form-item>
      <el-form-item :label="$t('device')+$t('linkage')">
        <el-switch
          v-model="device.canDeviceLinkage"
          :active-text="$t('open')"
          :inactive-text="$t('close')"
        />
      </el-form-item>
      <el-form-item :label="$t('map')">
        <div
          ref="register_device_map"
          style="height: 350px; width: 100%;"
        />
        <!--  搜索按钮 -->
        <div v-if="netModel !== 'local'">
          <div v-if="!enableSearch" class="map_search" @click="enableSearch = true">
            <span class="map_search_span el-icon-search" />
          </div>
          <!-- 搜索框-->
          <div v-else class="map_search_index">
            <div class="map_search_frame">
              <input
                v-model="keyword"
                type="text"
                class="map_search_frame_input"
                :placeholder="$t('city')"
              >
              <i class="map_search_frame_btn el-icon-search" @click="searchKeyword" />
            </div>
            <div
              v-if="searchPointList.length > 0"
              style="background: #FFF;height: 200px"
              class="uni-scroll"
            >
              <div
                v-for="(item,index) in searchPointList"
                :key="index"
              >
                <div
                  style="margin: 13px"
                  @click="pointClick(item)"
                >
                  {{ item.name }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" class="input-group" @click="addDevice">{{ $t("add") }}</el-button>
      </el-form-item>

      <el-dialog

        :title="$t('add')+$t('series')"
        :visible.sync="dialogAddProductSeriesFormVisible"
      >
        <el-form
          label-width="120px"
          :model="series"
        >
          <el-form-item :label="$t('name')">
            <el-input v-model="series.name" />
          </el-form-item>
          <el-form-item :label="$t('keyName')">
            <el-input v-model="series.keyName" />
          </el-form-item>
          <el-form-item :label="$t('remark')">
            <el-input v-model="series.remark" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogAddProductSeriesFormVisible = false">{{ $t("cancel") }}</el-button>
          <el-button type="primary" @click="addProductSeries">{{ $t("confirm") }}</el-button>
        </div>
      </el-dialog>
    </el-form>
  </div>
</template>

<script>
import {
  failureNotice,
  successNotice
} from '@/util/common'
import { registerDevice } from '@/api/iot/iotDeviceApi'
import { listProductTemplateDevice } from '@/api/iot/iotProductTemplateDeviceApi'
import { listProduct } from '@/api/iot/iotProductApi'
import { listDeviceServer } from '@/api/iot/iotDeviceServerApi'
import { getSeriesList, insertSeries } from '@/api/iot/iotProductSeriesApi'
import { getNetModel, getUserId } from '@/util/storage'
import { listDeviceIcon } from '@/api/iot/iotDeviceApi'
import { addMapClickListener, clearAndMakeMarket, makeMap, makeMarket } from '@/util/mapTool'
import { listCodec } from '@/api/iot/iotCodecApi'
export default {
  name: 'RegisterDevice',
  data() {
    return {
      device: {
        productId: null,
        serverId: null,
        seriesId: null,
        lat: null,
        lng: null,
        deviceName: '',
        protocol: '',
        deviceCore: '',
        remark: '',
        iconUrl: '',
        userId: getUserId(),
        sendInterval: 3,
        canDeviceLinkage: 0
      },
      productList: [],
      productSeriesList: [],
      serverList: [],
      searchService: null,
      markers: [],
      isIconOpen: false,
      mapSearchStyle: { color: 'red' },
      dialogAddProductSeriesFormVisible: false,
      series: {
        name: '',
        remark: ''
      },
      enableSearch: false,
      coreTips: [],
      nameRuleList: [],
      iconList: [],
      keyword: '',
      searchPointList: [],
      searchPointMarker: null,
      map: {},
      netModel: getNetModel(),
      protocolList: [],
    }
  },
  mounted() {
    this.listCodec()
    this.listProduct()
    this.listDeviceServer()

    this.map = makeMap(this.$refs.register_device_map, this.device.lat, this.device.lng, 13)
    makeMarket(this.map, this.device.lat, this.device.lng)
    const that = this
    addMapClickListener(this.map, (e) => {
      that.device.lat = e.latLng.lat
      that.device.lng = e.latLng.lng
      clearAndMakeMarket(that.map, that.device.lat, that.device.lng)
    })
    listDeviceIcon({
    }).then(res => {
      const { code, data } = res
      if (code === '200') {
        this.iconList = data
        this.dialogIconFormVisible = true
      }
    })
  },
  methods: {
    queryProtocolSearch(queryString, cb) {
      const protocolList = this.protocolList
      const results = queryString ? protocolList.filter(this.createProtocolFilter(queryString)) : protocolList
      // 调用 callback 返回建议列表的数据
      cb(results)
    },
    createProtocolFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
      }
    },
    listCodec() {
      listCodec().then(res => {
        const { code, data } = res
        const protocolList = []
        if (code === '200') {
          data.forEach(item => {
            this.device.protocol = item
            protocolList.push({
              label: item,
              value: item
            })
          })
        }
        this.protocolList = protocolList
      })
    },
    pointClick(item) {
      if (this.searchPointMarker != null) {
        this.searchPointMarker.setMap(null)
      }
      const latlngBounds = new window.qq.maps.LatLngBounds()
      // 扩展边界范围，用来包含搜索到的Poi点
      latlngBounds.extend(item.latLng)
      const marker = makeMarket(this.map, item.latLng.lat, item.latLng.lng)
      // 调整地图视野
      this.searchPointMarker = marker
      this.device.lat = item.latLng.lat
      this.device.lng = item.latLng.lng
      this.map.fitBounds(latlngBounds)
      this.enableSearch = false
    },
    // 设置搜索的范围和关键字等属性
    searchKeyword() {
      const that = this
      // 根据输入的城市设置搜索范围
      const searchService = new window.qq.maps.SearchService({
        complete(results) {
          // 设置回调函数参数
          switch (results.type) {
            case 'CITY_LIST':// POI检索结果城市列表。
              searchService.setLocation(results.detail.cities[0].cityName)
              searchService.search(that.keyword)
              break
            case 'POI_LIST':// POI列表。
            case 'AREA_INFO'://	行政区划信息。
            case 'GEO_INFO':// 地理位置信息。
              that.searchPointList = results.detail.pois
          }
        },
        // 若服务请求失败，则运行以下函数
        error() {
          failureNotice(that)
        }
      })
      searchService.search(this.keyword)
    },
    querySearch(queryString, cb) {
      cb(this.coreTips)
    },
    deviceCoreSelect(item) {
      if (this.device.deviceName === '') {
        for (let i = 0; i < this.nameRuleList.length; i++) {
          if (this.nameRuleList[i].keyName === item.value) {
            this.device.deviceName = this.nameRuleList[i].name
            this.device.protocol = this.nameRuleList[i].protocol
            this.device.canDeviceLinkage = this.nameRuleList[i].canDeviceLinkage
            break
          }
        }
      }
    },
    listProductTemplateDevice() {
      listProductTemplateDevice({
        productId: this.device.productId
      }).then(res => {
        const { code, data } = res
        if (code === '200') {
          const nameRuleList = data
          const coreTips = []
          for (let i = 0; i < nameRuleList.length; i++) {
            coreTips.push({ value: nameRuleList[i].keyName })
          }
          this.coreTips = coreTips
          this.nameRuleList = nameRuleList
        } else {
          this.coreTips = null
          failureNotice(this)
        }
      })
    },
    clickProductSeries() {
      this.dialogAddProductSeriesFormVisible = true
    },
    addProductSeries() {
      insertSeries({
        name: this.series.name,
        keyName: this.series.keyName,
        productId: this.device.productId,
        remark: this.series.remark
      }).then(res => {
        const { code } = res
        if (code === '200') {
          this.dialogAddProductSeriesFormVisible = false
          this.getSeriesList()
          successNotice(this)
        }
      })
    },

    addDevice() {
      if (this.device.deviceName === '') {
        this.$notify.error({
          title: '错误',
          message: '设备名不能为空'
        })
        return
      }
      if (this.device.deviceCore === '') {
        this.$notify.error({
          title: '错误',
          message: '设备唯一码不能为空'
        })
        return
      }
      if (this.device.lat == null) {
        this.$notify.error({
          title: '错误',
          message: '请在地图上选择设备坐标'
        })
        return
      }
      if (this.device.seriesId == null) {
        this.$notify.error({
          title: '错误',
          message: '必须选择系列'
        })
        return
      }
      if (this.device.serverId == null) {
        this.$notify.error({
          title: '错误',
          message: '必须选择传输媒体'
        })
        return
      }
      const json = {
        ...this.device
      }
      registerDevice(json).then(res => {
        const { code, msg } = res
        if (code === '200') {
          successNotice(this)
          const that = this
          this
            .$confirm(
              this.$t('manage') + this.device.deviceName,
              this.$t('prompt'),
              {
                confirmButtonText: this.$t('confirm'),
                cancelButtonText: this.$t('cancel'),
                type: 'warning'
              }
            )
            .then(function() {
              that.$router.push({
                path: '/device/manage/:deviceCore',
                query: {
                  deviceCore: that.device.deviceCore,
                  deviceName: that.device.deviceName
                }
              })
            })
            .catch(function() {})
        } else {
          failureNotice(this,msg)
        }
      })
    },
    choseIcon() {
      if (this.isIconOpen) {
        this.isIconOpen = false
      } else {
        this.isIconOpen = true
      }
    },
    changeIco(iconUrl) {
      this.isIconOpen = false
      this.device.iconUrl = iconUrl
    },
    getSeriesList() {
      getSeriesList({
        productId: this.device.productId
      }).then(res => {
        const { code, data } = res
        if (code === '200') {
          this.productSeriesList = data
          this.device.seriesId = data[0].seriesId
        } else {
          this.productSeriesList = []
          failureNotice(this)
        }
      })
    },
    productChange(val) {
      this.device.productId = val
      this.device.seriesId = null
      this.getSeriesList()
      this.listProductTemplateDevice()
    },
    listProduct() {
      listProduct(null).then(res => {
        const { code, data } = res
        if (code === '200') {
          this.device.productId = data[0].productId
          this.productList = data
          this.getSeriesList()
          this.listProductTemplateDevice()
        }
      })
    },
    listDeviceServer() {
      listDeviceServer(null).then(res => {
        const { code, data } = res
        if (code === '200') {
          this.serverList = data
          this.device.serverId = data[0].serverId
        }
      })
    }
  }
}
</script>
<style scoped>
  #register_device_map {
    width: 100%;
    height: 100%;
    overflow: hidden;
    margin: 0;
    font-family: "微软雅黑";
  }

  .map_search {
    position: absolute;
    top: 13px;
    left: 13px;
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background-color: rgba(225, 225, 225, 0.8);
    z-index: 10;
    box-shadow: 0 0 13px rgba(225, 225, 225, 0.6);
    cursor: pointer;
  }

  .map_search_span {
    position: absolute;
    top: 10px;
    left: 10px;
    font-size: 1.5em;
  }

  .map_search_index {
    position: absolute;
    top: 13px;
    left: 13px;
    width: 340px;
    height: auto;
    overflow: hidden;
    z-index: 10;
  }

  .map_search_frame {
    position: relative;
    width: 340px;
    height: 45px;
    line-height: 45px;
    background-color: rgba(225, 225, 225, 0.8);
    box-shadow: 0 0 13px rgba(225, 225, 225, 0.6);
  }

  .map_search_frame_input {
    position: absolute;
    top: 7px;
    left: 13px;
    width: 270px;
    height: 30px;
    line-height: 30px;
    border: none;
    border-radius: 4px;
    padding: 0 20px;
  }

  .map_search_frame_btn {
    position: absolute;
    top: 9px;
    right: 12px;
    width: 30px;
    height: 26px;
    font-size: 1.6em;
  }

</style>
